<template>
  <VueMarkdownEditor
    v-bind="$attrs"
    v-model="value"
    :height="height + 'px'"
    :include-level="[1, 2, 3, 4, 5, 6]"
    @upload-image="handleUploadImage"
  ></VueMarkdownEditor>
</template>

<script setup lang="ts">
import { computed } from 'vue'

import { uploadImg } from '@/api/common'

import VueMarkdownEditor from '@kangc/v-md-editor'
import '@kangc/v-md-editor/lib/style/base-editor.css'
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js'
import '@kangc/v-md-editor/lib/theme/style/vuepress.css'

import Prism from 'prismjs'

VueMarkdownEditor.use(vuepressTheme, {
  Prism
})

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: Number,
    default: 500
  },
  http: {
    type: Function,
    default: uploadImg
  }
})

const emts = defineEmits({
  'update:modelValue': (val) => !!val
})

const value = computed({
  get: () => {
    return props.modelValue
  },
  set: (val) => {
    emts('update:modelValue', val)
  }
})

const handleUploadImage = async (event: any, insertImage: any, files: any) => {
  event.preventDefault()
  const file = files[0]
  const formData = new FormData()
  formData.append('files', file)
  props
    .http(formData)
    .then((res: any) => {
      insertImage({
        url: res.data?.url
      })
    })
    .catch((err: any) => {
      console.error(err, 'err')
    })
}

defineOptions({
  name: 'v-md-editor'
})
</script>

<style scoped></style>
